const { query } = require("./db");
const routes = {};
routes["getByKeyStrEqual"] = (req, res) => {
  console.log(req.query.str);
  const str = req.query.str;
  query(`SELECT * FROM ENWORDS WHERE word = '${str}' limit 20`, res);
};
function isChinese(str) {
  // 将中文字符的Unicode编码范围定义为正则表达式
  const reg = /^[\u4E00-\u9FA5]+$/;
  // 使用正则表达式的test方法进行检测
  return reg.test(str);
}

routes["getByKeyStrSimilary"] = (req, res) => {
  const onlyIELST = req.query.onlyIELST;
  const onlyOK = req.query.onlyOK;
  const str = req.query.str;
  if(isChinese(str)){
    query(
      `SELECT * FROM ENWORDS WHERE trans like '%${str}%'
        ${onlyIELST === "true" ? " and ielst = 'YES'" : " and 1=1 "} 
        ${onlyOK === "true" ? " and ok = 'OK'" : " and 1=1 "}  
        order by trans <-> '${str}' limit 20`,
      res
    );
    return;
  }
  query(
    `SELECT * FROM ENWORDS 
        where word <> '${str}'
        ${onlyIELST === "true" ? " and ielst = 'YES'" : " and 1=1 "} 
        ${onlyOK === "true" ? " and ok = 'OK'" : " and 1=1 "} 
        order by word <-> '${str}' limit 20`,
    res
  );
};
routes["getByKeyStrInclude"] = (req, res) => {
  const str = req.query.str;
  const onlyIELST = req.query.onlyIELST;
  const onlyOK = req.query.onlyOK;
  query(
    `SELECT * FROM ENWORDS WHERE
    word <> '${str}'
    ${onlyIELST === "true" ? " and ielst = 'YES'" : "and 1=1"} 
    ${onlyOK === "true" ? " and ok = 'OK'" : "and 1=1"} 
    and word like '%${str}%' order by length(word) limit 20`,
    res
  );
};
routes["getByKeyStrPrefix"] = (req, res) => {
  const str = req.query.str;
  const onlyIELST = req.query.onlyIELST;
  const onlyOK = req.query.onlyOK;
  query(
    `SELECT * FROM ENWORDS WHERE 
    word <> '${str}' 
    ${onlyIELST === "true" ? " and ielst = 'YES'" : "and 1=1"} 
    ${onlyOK === "true" ? " and ok = 'OK'" : "and 1=1"} 
    and 
    word like '${str}%' limit 20`,
    res
  );
};
routes["getByKeyStrsuffix"] = (req, res) => {
  const str = req.query.str;
  const onlyIELST = req.query.onlyIELST;
  const onlyOK = req.query.onlyOK;
  query(
    `SELECT * FROM ENWORDS WHERE
    word <> '${str}' 
    ${onlyIELST === "true" ? " and ielst = 'YES'" : "and 1=1"} 
    ${onlyOK === "true" ? " and ok = 'OK'" : "and 1=1"} 
    and 
    word like '%${str}' limit 20`,
    res
  );
};
routes["setOK"] = (req, res) => {
  const str = req.query.str;
  query(`UPDATE ENWORDS SET ok = 
    (
        case when ok = 'OK' then 'NO' 
        else 'OK'
        end
    )
    where word = '${str}'`, res);
};

function registerRoutes(app) {
  Object.keys(routes).map((key) => {
    console.log(`api registered : ${key}`);
    app.get(`/${key}`, routes[key]);
  });
}

module.exports = registerRoutes;
